package com.example.demo;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonArray;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.sql.*;
import java.util.*;

@RestController
public class DetailPost {

    @PostMapping("/getPostDetail")//url: 'http://localhost:8080/post/detail'
    public JSONObject DetailPost(@RequestBody JSONObject requestBody) throws SQLException {
        String postid= (String) requestBody.get("postid");
        String wxid= (String) requestBody.get("wxid");
        //return  ResponseEntity.ok(queryDb(postid));
        //return ResponseEntity.ok("Post added successfully");
        System.out.println(queryDb(postid,wxid));
        return queryDb(postid,wxid);
    }

    public static JSONObject queryDb(String postid,String wxid) throws SQLException {
        Connection con=null;
        JSONObject data  = new JSONObject();
        PreparedStatement preparedStatement = null;
        try {
            String driver = "com.mysql.cj.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/jidazhidemai";

            // 数据库的用户名与密码，需要根据自己的设置
            String user = "root";
            String password = "gFL123456";
            Class.forName(driver);
            //注册JDBC驱动程 序
            //建立连接
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("数据库连接成功");
            }

            //Statement stmt = con.createStatement();
//            String sql = "INSERT INTO tab1 (title,author,submission_date) VALUES ('li','xiao','2020-07028')";
            String sql = " select * from post where postid=?;";
            preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, postid);
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                String title = rs.getString("name");
                String location = rs.getString("location");
                String oldprice = rs.getString("oldprice");
                String newprice = rs.getString("newprice");
                String posterUsername = queryuser_name(rs.getString("posterid"));
                String desc = rs.getString("desc");
                int upvote = rs.getInt("like");
                int downvote = rs.getInt("dislike");
                Boolean fav = queryfav(wxid, postid);
                String comments = rs.getString("comments");
                JSONArray arrayPlayer = new JSONArray();
                arrayPlayer = JSONArray.parseArray(comments);
                if(arrayPlayer==null){
                    arrayPlayer = new JSONArray();
                }
                System.out.println(fav);
                data.put("title", title);
                data.put("location", location);
                data.put("oldprice", oldprice);
                data.put("newprice", newprice);
                data.put("posterName", posterUsername);
                data.put("posterID", rs.getString("posterid"));
                data.put("desc", desc);
                data.put("upvote", upvote);
                data.put("downvote", downvote);
                data.put("comments", arrayPlayer);
                data.put("status", "COMPLETE");
                data.put("fav", fav);
                boolean isHighlight=isHighlight(postid);
                data.put("isHighlight", isHighlight);
                String sql4="select votes from `user` where wxid=?";
                int vote=1;
                PreparedStatement stmt4 = con.prepareStatement(sql4);
                stmt4.setString(1, wxid);
                ResultSet rs4 = stmt4.executeQuery();
                String userOldVotes=null;
                while (rs4.next()){
                    userOldVotes=rs4.getString("votes");
                    if(userOldVotes==null){
                        vote=0;
                        break;
                    }
                    List<String> postIds =new ArrayList<>();
                    postIds= new ArrayList<String>(Arrays.asList(userOldVotes.split("_")));
                    if(postIds.contains("{postid:"+postid+",vote:"+vote+"}")){
                        vote=1;
                    }
                    else if(postIds.contains("{postid:"+postid+",vote:"+(-vote)+"}")){
                        vote=-1;
                    }else
                        vote=0;
                }
                data.put("vote",vote);

            }
            con.close();
            return data;

        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动没有安装");

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        data.put("status", "FAIL_NOMATCH");
        return data;
    }

        public static String queryuser_name (String userid){
            Connection con;
            try {
                String driver = "com.mysql.cj.jdbc.Driver";
                String url = "jdbc:mysql://localhost:3306/jidazhidemai";

                // 数据库的用户名与密码，需要根据自己的设置
                String user = "root";
                String password = "gFL123456";
                Class.forName(driver);
                //注册JDBC驱动程 序
                //建立连接
                con = DriverManager.getConnection(url, user, password);
                if (!con.isClosed()) {
                    System.out.println("数据库连接成功");
                }

                //Statement stmt = con.createStatement();
//            String sql = "INSERT INTO tab1 (title,author,submission_date) VALUES ('li','xiao','2020-07028')";
                String sql = " select username from user where userid=?;";
                PreparedStatement preparedStatement = con.prepareStatement(sql);
                preparedStatement.setString(1, userid);
                ResultSet rs = preparedStatement.executeQuery();
                while (rs.next()) {
                    String user_name = rs.getString("username");
                    con.close();
                    return user_name;
                }

            } catch (ClassNotFoundException e) {
                System.out.println("数据库驱动没有安装");

            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("数据库连接失败");
            }
            return "False-出错了！";
        }
        public static boolean queryfav (String wxid, String postid){
            Connection con;
            try {
                String driver = "com.mysql.cj.jdbc.Driver";
                String url = "jdbc:mysql://localhost:3306/jidazhidemai";

                // 数据库的用户名与密码，需要根据自己的设置
                String user = "root";
                String password = "gFL123456";
                Class.forName(driver);
                //注册JDBC驱动程 序
                //建立连接
                con = DriverManager.getConnection(url, user, password);
                if (!con.isClosed()) {
                    System.out.println("数据库连接成功");
                }

                //Statement stmt = con.createStatement();
//            String sql = "INSERT INTO tab1 (title,author,submission_date) VALUES ('li','xiao','2020-07028')";
                String sql = " select fav from user where wxid=?;";
                PreparedStatement preparedStatement = con.prepareStatement(sql);
                preparedStatement.setString(1, wxid);
                ResultSet rs = preparedStatement.executeQuery();
                while (rs.next()) {
                    String fav = rs.getString("fav");
                    if(fav==null){
                        con.close();
                        return false;
                    }
                    List<String> result = new ArrayList<String>(Arrays.asList(fav.split(",")));
                    System.out.println("getDetail"+result);
                    System.out.println(postid);
                    if (result.contains(postid)) {
                        System.out.println(true);
                        con.close();
                        return true;
                    } else {
                        con.close();
                        return false;
                    }
                }


            } catch (ClassNotFoundException e) {
                System.out.println("数据库驱动没有安装");

            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("数据库连接失败");
            }

            return false;
        }
    public static boolean isHighlight(String postid){
        Connection con;
        try {
            //注册JDBC驱动程 序
            String driver = "com.mysql.cj.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/jidazhidemai";

            // 数据库的用户名与密码，需要根据自己的设置
            String user = "root";
            String password = "gFL123456";
            Class.forName(driver);
            //建立连接
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("数据库连接成功");
            }

            String sql = "select * from highlight where postid=? limit 1";
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, postid);
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                return true;
            }
            con.close();

        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动没有安装");

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        return false;
    }
}